package com.zhouixi.handler;

import com.alibaba.fastjson.JSONObject;
import com.zhouixi.entity.LocalMessageQueue;
import com.zhouixi.entity.Message;
import com.zhouixi.repository.NodeRegistry;
import com.zhouixi.repository.SessionManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 用户处理器
 */
@Component
@Slf4j
public class WebSocketHandler {

    @Resource
    private SessionManager sessionManager ;

    public boolean sendToUser(Long userId, String content) {
        Message message = JSONObject.parseObject(content, Message.class);
        WebSocketSession session = sessionManager.getSession(message.getReceiverId());
        if (session != null && session.isOpen()) {
            try {
                log.info("收到消息：{}",message);
                session.sendMessage(new TextMessage(message.getContent()));
                return true ;
            } catch (IOException e) {
                log.error("发送消息失败了");
                return false;
            } catch (Exception e) {
                // 处理其他异常
                log.error("Unexpected error while sending message to user {}: {}", userId, e.getMessage());
            }
        }
        return false ;
    }

    public void registerSession(Long userId, WebSocketSession session) {
        sessionManager.addSession(userId, session);
    }

    public void removeSession(Long userId) {
        sessionManager.removeSession(userId);
    }
}
